/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.edu.iuh.dhth7dlt.emailclient.ui;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import org.apache.james.mime4j.MimeException;
import vn.edu.iuh.dhth7dlt.emailclient.utils.ConfigAccount;
import vn.edu.iuh.dhth7dlt.emailclient.utils.Email;
import vn.edu.iuh.dhth7dlt.emailclient.utils.EmailExceptions;
import vn.edu.iuh.dhth7dlt.emailclient.utils.FileHelper;
import vn.edu.iuh.dhth7dlt.emailclient.utils.Messenger;
import vn.edu.iuh.dhth7dlt.emailclient.utils.POP;
import vn.edu.iuh.dhth7dlt.emailclient.utils.SqliteHelper;

/**
 *
 * @author Friendless
 */
public class MainForm extends javax.swing.JFrame {

    /**
     * Khai báo biến ban đầu
     */
    ArrayList<Email> emails;
    SqliteHelper sqliteHelper;
    DefaultTableModel dataModel;
    SendEmail se;
    int index;//Vi trí dòng chọn
    ConfigAccount currentAccount;//Tài khoản hiện tại đang chọn
    ArrayList<ConfigAccount> accounts;
    private TableRowSorter<DefaultTableModel> sorter;
    HashMap<String, String> paramsAccount;
    public static MainForm frm = null;
    int action = 1;

    /**
     * Creates new form MainForm
     */
    public MainForm() throws ClassNotFoundException, IOException, SQLException, MimeException, MimeException, ParseException, ParseException {
        initComponents();
        makeTree();
        dataModel = new DefaultTableModel();
        sorter = new TableRowSorter<>(dataModel);
        jListEmail.setRowSorter(sorter);
        //full row select
        jListEmail.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jListEmail.setCellSelectionEnabled(false);
        jListEmail.setRowSelectionAllowed(true);
        jListEmail.setColumnSelectionAllowed(false);
        //full screen
        setExtendedState(JFrame.MAXIMIZED_BOTH);

    }

    private void loadDataTable(int action) throws ClassNotFoundException, SQLException, IOException, MimeException, ParseException {
        sqliteHelper = new SqliteHelper(currentAccount.getPathDB());
        emails = sqliteHelper.getAllEmail(action);
        String[] colNames = {"Người Gửi", "Tiêu Đề", "Ngày Gửi"};
        dataModel.setColumnIdentifiers(colNames);
        dataModel.setRowCount(0);
        int colCount = colNames.length;
        for (int i = 0; i < emails.size(); i++) {
            String[] rowData = new String[colCount];
            Email e = emails.get(i);
            rowData[0] = "<HTML>" + e.getSenderFrom() + "</HTML>";
            rowData[1] = e.getSubject();
            rowData[2] = e.getDate().toString();
            dataModel.addRow(rowData);
        }
        jListEmail.setModel(dataModel);
        jListEmail.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                index = jListEmail.getSelectedRow();
                if (index != -1) {
                    Email email = emails.get(index);
                    jBodyEmail.setText(email.getTexttBody());
                    lblHeader.setText(String.format("<HTML><B>Người Gửi</B>:%s<BR><B>Người Nhận</B>:"
                            + "%s<B>&nbsp;&nbsp;&nbsp;&nbsp;Đồng Gửi</B>:%s<BR><B>Tiêu Đề:</B>%s</HTML>",
                            email.getSenderFrom(), email.getSenderTo(), email.getCC(), email.getSubject()));
                }

            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSeparator2 = new javax.swing.JSeparator();
        jToolBar1 = new javax.swing.JToolBar();
        btnCheck = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnCompose = new javax.swing.JButton();
        btnReply = new javax.swing.JButton();
        btnReplyAll = new javax.swing.JButton();
        btnForward = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        treeListAccount = new javax.swing.JTree();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jSplitPane2 = new javax.swing.JSplitPane();
        jScrollPane4 = new javax.swing.JScrollPane();
        jListEmail = new javax.swing.JTable();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jBodyEmail = new javax.swing.JEditorPane();
        lblHeader = new javax.swing.JLabel();
        txtTim = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        btnTim = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JSeparator();
        jMenuBar1 = new javax.swing.JMenuBar();
        menuCauHinh = new javax.swing.JMenu();
        menuTaiKhoan = new javax.swing.JMenuItem();
        jMenuDeleteAccount = new javax.swing.JMenuItem();
        menuTroGiup = new javax.swing.JMenu();
        menuVeTacGia = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("iEmail Client  - Nhóm 8");

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        btnCheck.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vn/edu/iuh/dhth7dlt/emailclient/images/check.png"))); // NOI18N
        btnCheck.setText("Kiểm tra thư");
        btnCheck.setFocusable(false);
        btnCheck.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnCheck.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnCheck.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCheckActionPerformed(evt);
            }
        });
        jToolBar1.add(btnCheck);

        btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vn/edu/iuh/dhth7dlt/emailclient/images/delete.png"))); // NOI18N
        btnDelete.setText("Xóa Thư");
        btnDelete.setFocusable(false);
        btnDelete.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnDelete.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });
        jToolBar1.add(btnDelete);

        btnCompose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vn/edu/iuh/dhth7dlt/emailclient/images/compose.png"))); // NOI18N
        btnCompose.setText("Soạn Thư");
        btnCompose.setFocusable(false);
        btnCompose.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnCompose.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnCompose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnComposeActionPerformed(evt);
            }
        });
        jToolBar1.add(btnCompose);

        btnReply.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vn/edu/iuh/dhth7dlt/emailclient/images/reply.png"))); // NOI18N
        btnReply.setText("Reply");
        btnReply.setFocusable(false);
        btnReply.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnReply.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnReply.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnReplyActionPerformed(evt);
            }
        });
        jToolBar1.add(btnReply);

        btnReplyAll.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vn/edu/iuh/dhth7dlt/emailclient/images/reply_all.png"))); // NOI18N
        btnReplyAll.setText("Reply Tất Cả");
        btnReplyAll.setFocusable(false);
        btnReplyAll.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnReplyAll.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnReplyAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnReplyAllActionPerformed(evt);
            }
        });
        jToolBar1.add(btnReplyAll);

        btnForward.setIcon(new javax.swing.ImageIcon(getClass().getResource("/vn/edu/iuh/dhth7dlt/emailclient/images/forward.png"))); // NOI18N
        btnForward.setText("Chuyển Tiếp");
        btnForward.setFocusable(false);
        btnForward.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnForward.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnForward.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnForwardActionPerformed(evt);
            }
        });
        jToolBar1.add(btnForward);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 18, Short.MAX_VALUE)
        );

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        treeListAccount.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jScrollPane1.setViewportView(treeListAccount);

        jSplitPane1.setLeftComponent(jScrollPane1);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 23, Short.MAX_VALUE)
        );

        jSplitPane2.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jScrollPane4.setMinimumSize(new java.awt.Dimension(23, 200));

        jListEmail.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Người Gửi", "Tiêu Đề", "Thời Gian"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jListEmail.setColumnSelectionAllowed(true);
        jListEmail.setMinimumSize(new java.awt.Dimension(45, 100));
        jListEmail.setName(""); // NOI18N
        jListEmail.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jListEmail.getTableHeader().setReorderingAllowed(false);
        jListEmail.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListEmailMouseClicked(evt);
            }
        });
        jScrollPane4.setViewportView(jListEmail);
        jListEmail.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);

        jSplitPane2.setLeftComponent(jScrollPane4);

        jScrollPane2.setViewportView(jBodyEmail);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2)
            .addComponent(lblHeader, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(lblHeader, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE))
        );

        jSplitPane2.setRightComponent(jPanel4);

        btnTim.setText("Lọc");
        btnTim.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTimActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane2, javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(txtTim, javax.swing.GroupLayout.PREFERRED_SIZE, 314, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnTim)
                        .addGap(108, 108, 108)
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jSeparator1)))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtTim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnTim)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE))
        );

        jSplitPane1.setRightComponent(jPanel2);

        menuCauHinh.setText("Cấu Hình");

        menuTaiKhoan.setText("Tài Khoản");
        menuTaiKhoan.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuTaiKhoanActionPerformed(evt);
            }
        });
        menuCauHinh.add(menuTaiKhoan);

        jMenuDeleteAccount.setText("Xóa Tài Khoản");
        jMenuDeleteAccount.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuDeleteAccountActionPerformed(evt);
            }
        });
        menuCauHinh.add(jMenuDeleteAccount);

        jMenuBar1.add(menuCauHinh);

        menuTroGiup.setText("Trợ Giúp");

        menuVeTacGia.setText("Về Tác Giúp");
        menuVeTacGia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuVeTacGiaActionPerformed(evt);
            }
        });
        menuTroGiup.add(menuVeTacGia);

        jMenuBar1.add(menuTroGiup);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(794, 794, 794))
            .addComponent(jSplitPane1)
            .addComponent(jSeparator3, javax.swing.GroupLayout.Alignment.TRAILING)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCheckActionPerformed
        try {

            paramsAccount = new HashMap<>();
            paramsAccount.put("PopServer", currentAccount.getPOPserver());
            paramsAccount.put("port", String.valueOf(currentAccount.getPOPport()));
            paramsAccount.put("user", currentAccount.getUser());
            paramsAccount.put("pass", currentAccount.getPassword());
            paramsAccount.put("pathDB", currentAccount.getPathDB());
            if (paramsAccount.containsValue("")) {
                System.out.println("Truyền thiếu giá trị.");
                return;
            }
            sqliteHelper = new SqliteHelper(currentAccount.getPathDB());
            POP getMail = new POP(paramsAccount);
            getMail.getUpdateEmail();
            try {
                loadDataTable(action);
            } catch (MimeException | ParseException ex) {
                Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (SQLException | ClassNotFoundException | IOException | EmailExceptions ex) {
            Logger.getLogger(MainForm.class
                    .getName()).log(Level.SEVERE, null, ex);
        }



    }//GEN-LAST:event_btnCheckActionPerformed

    private void jListEmailMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListEmailMouseClicked
//        int index = jListEmail.getSelectedRow();
//        jBodyEmail.setText(emails.get(index).getTexttBody());
    }//GEN-LAST:event_jListEmailMouseClicked

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed

        try {
            sqliteHelper = new SqliteHelper(currentAccount.getPathDB());
        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {

            if (action != 3) {
                sqliteHelper.deleteEmailId(emails.get(index).getId());

            } else //Xóa thùng rác và trên server
            {
                boolean isDelete = sqliteHelper.deleteEmaiForever(emails.get(index).getId());
                //Messenger.show("isDelete:"+isDelete);
                try {
                    int idEmail = emails.get(index).getIdEmail();
                    if (!"0".equals(String.valueOf(idEmail))) {
                        paramsAccount = new HashMap<>();
                        paramsAccount.put("PopServer", currentAccount.getPOPserver());
                        paramsAccount.put("port", String.valueOf(currentAccount.getPOPport()));
                        paramsAccount.put("user", currentAccount.getUser());
                        paramsAccount.put("pass", currentAccount.getPassword());
                        paramsAccount.put("isSaveEmail", String.valueOf(currentAccount.isSaveMailOnServer()));
                        paramsAccount.put("pathDB", currentAccount.getPathDB());
                        if (paramsAccount.containsValue("")) {
                            System.out.println("Truyền thiếu giá trị.");
                            return;
                        }
                        POP p = new POP(paramsAccount);
                        p.delelteEmailByID("" + idEmail);
                        p.close();//Xác nhận xóa
                    }
                } catch (IOException | EmailExceptions ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            dataModel.removeRow(index);
        } catch (SQLException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            loadDataTable(action);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MimeException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        dataModel.fireTableDataChanged();
    }//GEN-LAST:event_btnDeleteActionPerformed

    private void btnComposeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnComposeActionPerformed
        // TODO add your handling code here:
        if (currentAccount == null) {
            Messenger.show("Vui lòng chọn tài khoản trước khi tiến hành gửi email");
            return;
        }
        se = new SendEmail(currentAccount);
        se.setVisible(true);

    }//GEN-LAST:event_btnComposeActionPerformed

    private void btnReplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnReplyActionPerformed
        // TODO add your handling code here:
         if (currentAccount == null) {
            Messenger.show("Vui lòng chọn tài khoản trước khi tiến hành gửi email");
            return;
        }
        se = new SendEmail(currentAccount);
        Email email = emails.get(index);
        se.jtxTo.setText(email.getSenderFrom());
        se.jtxTieuDe.setText("Về: " + email.getSubject());
        se.jtxNoiDung.setText(String.format("\n\n--------------------------------------------\n"
                + "Người Gửi: %s\nNgười Nhận: %s\nThời Gian: %s\nTiêu Đề: %s\n\n%s",
                email.getSenderFrom(), email.getSenderTo(), email.getDate(), email.getSubject(), email.getTexttBody()));
        se.setVisible(true);

    }//GEN-LAST:event_btnReplyActionPerformed

    private void btnReplyAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnReplyAllActionPerformed
       
         if (currentAccount == null) {
            Messenger.show("Vui lòng chọn tài khoản trước khi tiến hành gửi email");
            return;
        }
        se = new SendEmail(currentAccount);
        Email email = emails.get(index);
        se.jtxTo.setText(email.getSenderFrom());
        se.jtxCc.setText(email.getCC());
        se.jtxTieuDe.setText("Về: " + email.getSubject());
        se.jtxNoiDung.setText(String.format("\n\n--------------------------------------------\n"
                + "Người Gửi: %s\nNgười Nhận: %s\nThời Gian: %s\nTiêu Đề: %s\n\n%s",
                email.getSenderFrom(), email.getSenderTo(), email.getDate(), email.getSubject(), email.getTexttBody()));
        se.setVisible(true);
    }//GEN-LAST:event_btnReplyAllActionPerformed

    private void btnForwardActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnForwardActionPerformed
        if (currentAccount == null) {
            Messenger.show("Vui lòng chọn tài khoản trước khi tiến hành gửi email");
            return;
        }
        se = new SendEmail(currentAccount);
        Email email = emails.get(index);
        se.jtxTieuDe.setText("Chuyển tiếp: " + email.getSubject());
        se.jtxNoiDung.setText(String.format("\n\n-------------Thư đã chuyển tiếp-------------\n"
                + "Người Gửi: %s\nNgười Nhận: %s\nThời Gian: %s\nTiêu Đề: %s\n\n%s",
                email.getSenderFrom(), email.getSenderTo(), email.getDate(), email.getSubject(), email.getTexttBody()));
        se.setVisible(true);

    }//GEN-LAST:event_btnForwardActionPerformed

    private void menuTaiKhoanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuTaiKhoanActionPerformed
        // TODO add your handling code here:
        AddAccount ac = new AddAccount();
        if (currentAccount != null) {
            ac.jtxHoTen.setText(currentAccount.getName());
            ac.jtxEmail.setText(currentAccount.getEmail());
            ac.jtxTaiKhoan.setText(currentAccount.getUser());
            ac.jtxMatKhau.setText(currentAccount.getPassword());
            ac.jtxPop.setText(currentAccount.getPOPserver());
            ac.jtxPortPOP.setText("" + currentAccount.getPOPport());
            ac.jtxSMTP.setText(currentAccount.getSMTPserver());
            ac.jtxPortSMTP.setText("" + currentAccount.getSMTPport());
            ac.jtxNoiLuu.setText(currentAccount.getPathDB());
            ac.jchkSaveMail.setSelected(currentAccount.isSaveMailOnServer());
        }
        ac.setVisible(true);

    }//GEN-LAST:event_menuTaiKhoanActionPerformed

    private void menuVeTacGiaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuVeTacGiaActionPerformed
        // TODO add your handling code here:
        AboutEmailClient ab = new AboutEmailClient();
        ab.setVisible(true);
    }//GEN-LAST:event_menuVeTacGiaActionPerformed
    private void newFilter(boolean isFillter) {
        RowFilter<DefaultTableModel, Object> rf = null;
        //If current expression doesn't parse, don't update.
        try {
            rf = RowFilter.regexFilter(Pattern.compile(txtTim.getText(), Pattern.CASE_INSENSITIVE).toString(), 0, 1, 2);
        } catch (java.util.regex.PatternSyntaxException e) {
            return;
        }
        if (isFillter == false) {
            rf = null;
        }
        sorter.setRowFilter(rf);
    }
    boolean isFillter = true;
    private void btnTimActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTimActionPerformed

        newFilter(isFillter);
        btnTim.setText(isFillter == true ? "Thôi" : "Lọc");
        isFillter = !isFillter;
    }//GEN-LAST:event_btnTimActionPerformed

    private void jMenuDeleteAccountActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuDeleteAccountActionPerformed
        if (currentAccount == null) {
            return;
        }
        int reply = JOptionPane.showConfirmDialog(null, "Bạn muốn xóa tài khoản " + currentAccount.getEmail() + " ?", "Thông báo", JOptionPane.YES_NO_OPTION);
        if (reply == JOptionPane.YES_OPTION) {
            File f = new File("UserData\\" + currentAccount.getEmail() + ".dat");
            if (f.delete()) {
                Messenger.show("Xóa tài khoản thành công");
                makeTree();
            }
        }


    }//GEN-LAST:event_jMenuDeleteAccountActionPerformed
    //Hàm tạo menu bên trái

    public void makeTree() {
        try {
            accounts = FileHelper.getAccounts();
            AccountTreeModel treeModel = new AccountTreeModel(accounts);
            treeListAccount.setRootVisible(false);
            treeListAccount.setModel(treeModel);
            treeListAccount.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
            treeListAccount.addTreeSelectionListener(new TreeSelectionListener() {
                @Override
                public void valueChanged(TreeSelectionEvent e) {
                    if (treeListAccount.isSelectionEmpty()) {
                        return;
                    }
                    TreePath path = treeListAccount.getSelectionPath();
                    if (path.getParentPath() != null) {
                        if (path.getParentPath().getLastPathComponent() instanceof ConfigAccount) {
                            currentAccount = (ConfigAccount) path.getParentPath().getLastPathComponent();
                        } else if (path.getLastPathComponent() instanceof ConfigAccount) {
                            currentAccount = (ConfigAccount) path.getLastPathComponent();
                        }
                        //Sự kiện
                        try {
                            if (path.getLastPathComponent().equals("Họp Thư Đến")) {
                                action = 1;

                            }
                            if (path.getLastPathComponent().equals("Thư Đã Gửi")) {
                                action = 2;
                            }
                            if (path.getLastPathComponent().equals("Thùng Rác")) {
                                action = 3;
                            }
                            loadDataTable(action);
                        } catch (ClassNotFoundException | SQLException | IOException | MimeException | ParseException ex) {
                            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    }
                }
            });
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws IOException {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainForm.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainForm.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainForm.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainForm.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    frm = new MainForm();
                    frm.setVisible(true);

                } catch (SQLException ex) {
                    Logger.getLogger(MainForm.class
                            .getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(MainForm.class
                            .getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(MainForm.class
                            .getName()).log(Level.SEVERE, null, ex);
                } catch (MimeException ex) {
                    Logger.getLogger(MainForm.class
                            .getName()).log(Level.SEVERE, null, ex);
                } catch (ParseException ex) {
                    Logger.getLogger(MainForm.class
                            .getName()).log(Level.SEVERE, null, ex);
                }
            }
        });


    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCheck;
    private javax.swing.JButton btnCompose;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnForward;
    private javax.swing.JButton btnReply;
    private javax.swing.JButton btnReplyAll;
    private javax.swing.JButton btnTim;
    private javax.swing.JEditorPane jBodyEmail;
    private javax.swing.JTable jListEmail;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuDeleteAccount;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lblHeader;
    private javax.swing.JMenu menuCauHinh;
    private javax.swing.JMenuItem menuTaiKhoan;
    private javax.swing.JMenu menuTroGiup;
    private javax.swing.JMenuItem menuVeTacGia;
    private javax.swing.JTree treeListAccount;
    private javax.swing.JTextField txtTim;
    // End of variables declaration//GEN-END:variables
}
